//
//  ViewController.m
//  realmDemo
//
//  Created by Aaron Peng on 16/8/22.
//  Copyright © 2016年 BUPT. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"
#import "Dog.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}


- (IBAction)commitClick:(id)sender {
    Person *person = [[Person alloc] init];
    
    /**
     *  加载狗的数据
     */
    NSArray *dogs = [self loadDogsWithNames:self.dogsNameTextField.text];
    NSLog(@"%@", dogs);
    
    //给模型赋值
    RLMResults *allPersons = [Person allObjects];
    NSUInteger id = 0;
    for (Person *person in allPersons) {
        if (person.id > id) {
            id = person.id;
        }
    }
    person.id = id + 1;
    person.name = self.nameTextField.text;
    person.age = (int)(self.ageTextField.text).integerValue;
    person.isMale = self.genderSwitch.isOn;
    for (int i = 0; i < dogs.count; i++) {
        [person.dogs addObject:dogs[i]];
    }
    
    
    //写入数据库
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    //rlmObj就是上面的对象
    [realm addObject:person];
    [realm commitWriteTransaction];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSArray *)loadDogsWithNames:(NSString *)names {
    NSArray *namesArray = [names componentsSeparatedByString:@" "];
    
    NSMutableArray *array = [NSMutableArray array];
    
    if (![namesArray.firstObject isEqual: @""]) {
        RLMResults *allDogs = [Dog allObjects];
        NSUInteger cacheID = 0;
        for (Dog *dog in allDogs) {
            if (dog.id > cacheID) {
                cacheID = dog.id;
            }
        }
        for (int i = 0; i < namesArray.count; i++) {
            if (![namesArray[i] isEqual:@""]) {
                Dog *dog = [[Dog alloc] initWithValue:@[@(cacheID + i + 1), namesArray[i]]];
                [array addObject:dog];
            }
        }
    }
    
    return array.copy;
}

@end
